package com.lishem.leftgod.level1.class03;

/**
 * 顺时针从外向内转圈打印矩阵
 */
public class Code_07_PrintMatrixSpiralOrder {


    private static void spiralOrderPrint(int[][] matrix) {
        if (matrix == null) {
            return;
        }
        int left = 0, top = 0;
        int right = matrix[0].length - 1;
        int bottom = matrix.length - 1;

        int i = 0;
        while (left <= right && top <= bottom) {
            if (left == right) {
                // 一条竖线
                i = top;
                while (i <= bottom) {
                    System.out.println(matrix[i++][right] + " ");
                }
            } else if (top == bottom) {
                // 一条横线
                i = left;
                while (i <= right) {
                    System.out.println(matrix[top][i++] + " ");
                }
            } else {
                i = left;
                while (i < right) {
                    System.out.print(matrix[top][i++] + " ");
                }
                i = top;
                while (i < bottom) {
                    System.out.print(matrix[i++][right] + " ");
                }
                i = right;
                while (i > left) {
                    System.out.print(matrix[bottom][i--] + " ");
                }
                i = bottom;
                while (i > top) {
                    System.out.print(matrix[i--][left] + " ");
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }

    }


    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}};
        spiralOrderPrint(matrix);
    }


}
